<?php

class LoginController extends Zend_Controller_Action
{
    public function indexAction()
    {
        $this->_helper->layout->disableLayout();
    }

    public function logoutAction()
    {
        $user = Zend_Auth::getInstance()->getIdentity();

        if ($user)
        {
            $user->credential = NULL;
            $user->credential_expires = NULL;
            $user->save();
            Zend_Auth::getInstance()->clearIdentity();
        }

        setcookie('credential', '', time() - 60, '/', $_SERVER['HTTP_HOST']);

        if (Zend_Session::isDestroyed() == false)
            Zend_Session::destroy();

        $this->_redirect('/');
    }

    public function dologinAction()
    {
        $this->_helper->viewRenderer->setNoRender();
        if (!$this->getRequest()->isPost())
            return;

        $adapter = new CMS_Auth_Adapter($this->_getParam('user'), $this->_getParam('password'), true);

        try
        {
            $result = Zend_Auth::getInstance()->authenticate($adapter);

            if (Zend_Auth::getInstance()->hasIdentity())
            {
                $user = Zend_Auth::getInstance()->getIdentity();
                //Zend_Auth::getInstance()->clearIdentity();

                $this->_redirect('/home/index');
                return;
            }
        }
        catch (CMS_Auth_Exception $e)
        {
            switch ($e->getCode())
            {
                case CMS_Auth_Exception::ACCOUNT_NOT_FOUND:
                    $message = 'Nombre de usuario incorrecto.';
                    break;
                case CMS_Auth_Exception::WRONG_PASS:
                    $message = 'Contraseña incorrecta.';
                    break;
                case CMS_Auth_Exception::UKNOWN:
                default:
                    $message = 'Error desconocido. Por favor inténtelo nuevamente más tarde.';
            }
        }
        catch (Exception $e)
        {
            $message = $e->getMessage();
        }

        $this->view->message = $message;

        $this->_forward('/index', 'index');

    }

}